#include "stdafx.h"
#include "Nervus.h"

CNervus::CNervus(void)
{
	for( int i=0; i< NERVUS_ANTENNA_NUM; i++ )
	{
		m_pInputNervusAntenna[i] = new CNervusAntenna(this, 0);
		m_pOutputNervusAntenna[i] = new CNervusAntenna(this, i);
	}

	//m_bNoResponseStatus = false;
	//m_nExcitedCount = 0;
	//m_nSignalCount = 0;
	Complex CONST_CN;
	m_cValue = cn;
}


CNervus::~CNervus(void)
{
	for( int i=0; i< NERVUS_ANTENNA_NUM; i++ )
	{
		delete m_pInputNervusAntenna[i];
		delete m_pOutputNervusAntenna[i];
	}
}

void CNervus::ProcessSignal( void )
{
	Complex cResultSignal = m_pInputNervusAntenna[0]->GetSignal();

	for( int i=1; i< NERVUS_ANTENNA_NUM; i++ )
	{
	//TRACE(".bf combine :%lf,%lf [%lf]\n",cResultSignal.real, cResultSignal.image, cResultSignal.Model());
		if( !m_pInputNervusAntenna[i]->IsNotConnected() )
			cResultSignal.Combine( m_pInputNervusAntenna[i]->GetSignal(), m_cValue ).Square();
	//if( cResultSignal.real >1000 || cResultSignal.image>1000 || cResultSignal.real <-1000 || cResultSignal.image<-1000 )
		//TRACE("");
	}
	//TRACE("after combine :%lf,%lf [%lf]\n",cResultSignal.real, cResultSignal.image, cResultSignal.Model());
	//if( cResultSignal.real >1000 || cResultSignal.image>1000 || cResultSignal.real <-1000 || cResultSignal.image<-1000 )
		//TRACE("");

	for( int i=0; i< NERVUS_ANTENNA_NUM; i++ )
	{
		if( !m_pOutputNervusAntenna[i]->IsNotConnected() )
			m_pOutputNervusAntenna[i]->SetSignal( cResultSignal );
	}

	/*if( m_bNoResponseStatus )
	{
//TRACE("ExcitedCount:%d\n",m_nExcitedCount);
		for( int i=0; i< NERVUS_ANTENNA_NUM; i++ )
		{
			if( m_nExcitedCount < NERVUS_EXCITE_PERIOD )
				m_pOutputNervusAntenna[i]->SetSignal( GetExcitedOutput() );
			else
				m_pOutputNervusAntenna[i]->SetSignal( 0 );
		}
		if( m_nExcitedCount++ >= NERVUS_NO_RESPONSE_PERIOD )
			m_bNoResponseStatus = false;
		return;
	}
	else
	{
		for( int i=0; i< NERVUS_ANTENNA_NUM; i++ )
			m_nSignalCount += m_pInputNervusAntenna[i]->GetSignal();
//TRACE("SignalCount:%d\n",m_nSignalCount);
		if( m_nSignalCount >= NERVUS_EXCITE_LEVEL )
		{
			for( int i=0; i< NERVUS_ANTENNA_NUM; i++ )
			{
				m_pOutputNervusAntenna[i]->SetSignal( GetExcitedOutput() );
			}
			m_bNoResponseStatus = true;
			m_nExcitedCount = 1;
			m_nSignalCount = 0;
		}
	}*/
}

void CNervus::DoSignalTransmition( void )
{
	for( int i=0; i< NERVUS_ANTENNA_NUM; i++ )
	{
		//TRACE( "%d:%d.", i, m_pOutputNervusAntenna[i]->ReadCurrentSignal() );
		m_pOutputNervusAntenna[i]->TransmitSignal();
	}
	//TRACE(".");
}

void CNervusMap::ProcessSignal( void )
{
	for( int j=0; j<NERVUS_MAP_DEPTH; j++ )
		for( int i=0; i<NERVUS_MAP_WIDTH; i++ )
			if( m_pNervusPool[i][j] )
				m_pNervusPool[i][j]->ProcessSignal();

	for( int j=0; j<NERVUS_MAP_DEPTH; j++ )
		for( int i=0; i<NERVUS_MAP_WIDTH; i++ )
			if( m_pNervusPool[i][j] )
			{
				//TRACE("[%d,%d]", i, j);
				m_pNervusPool[i][j]->DoSignalTransmition();
			}
	//TRACE("\n");

}
